<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    function PriorityQueue() {
        // 属性封装
        this.items = [];

        // 队列元素
        function QueueElement(element, priority) {
            this.element = element;
            this.priority = priority;
        }

        // 添加方法
        PriorityQueue.prototype.enqueue = function (element, priority) {
            // 创建QueueElement对象
            var newQueueElement = new QueueElement(element, priority);
            if (this.items.length == 0) {
                this.items.push(newQueueElement);
            } else {
                var flag = false;
                for (let i = 0; i < this.items.length; i++) {
                    if (newQueueElement.priority < this.items[i].priority) {
                        this.items.splice(i, 0, newQueueElement);
                        flag = true
                        break;
                    }
                }
                if (!flag) {
                    this.items.push(newQueueElement);
                }
            }
        }
        // dequeue(): 移除队列的第一项，并返回被移除的元素
        PriorityQueue.prototype.dequeue = function () {
            return this.items.shift();
        }
        // front(): 返回队列中的第一个元素——最先被添加，也将是最先被移除的元素。队列不做任何变动
        PriorityQueue.prototype.front = function () {
            return this.items[0];
        }
        // isEmpty(): 判空
        PriorityQueue.prototype.isEmpty = function () {
            return this.items.length == 0;
        }
        // size(): 返回长度
        PriorityQueue.prototype.size = function () {
            return this.items.length;
        }
        // tostring(): 输出
        PriorityQueue.prototype.tostring = function () {
            var str = '';
            for (let index = 0; index < this.items.length; index++) {
                str += this.items[index].priority+","+this.items[index].element+ ' ';
            }
            return str;
        }
    }


    var nn=new PriorityQueue();
    nn.enqueue('abc',111);
    nn.enqueue('cba',200);
    nn.enqueue('nba',50);
    nn.enqueue('nba',66);
    console.log(nn.tostring());
</script>

</html>